#pragma once
#include <iostream>
#include <memory>
#include "Socket.hpp"
#include "Connection.hpp"
#include"Log.hpp"
#include"HandleConnection.hpp"
using namespace socket_ns;
static int test_num = 0;
class Listener
{
public:
    Listener(uint16_t port) : _port(port), _listensocket(std::make_unique<TcpSocket>())
    {
        _listensocket->BuildListenSocket(_port);
    }
    void Accepter(Connection *conn)
    {
        //LOG(INFO, "%d accept success\n", conn->Sockfd());
        //ET模式，每次必须保证读取完全，且fd得设置为非阻塞，否则读到空会阻塞
        while(true)
        {
       // LOG(DEBUG,"Testttttttttt num:%d",test_num);
        //test_num++;

            errno = 0;
            InetAddr client;
            int code = 0;
            int sockfd = _listensocket->Acceptor(&client,&code);
            if(sockfd > 0)
            {
                //获取新连接，通过conn里的reactor封装
                LOG(INFO,"获取新连接,ip:%s,port:%d,文件描述符：%d",client.Ip().c_str(),client.Port(),sockfd);
                //封装普通连接，并且添加回调方法！
                conn->_R->AddConnection(sockfd,EPOLLIN|EPOLLET,client,NormalType);//这里的设计太巧妙了！
                //return ;
            }
            else
            {
                //读取完毕

                if(code == EWOULDBLOCK)
                {
                    LOG(INFO,"读取完毕");
                    break;
                }
                //信号中断
                else if(code == EINTR)
                {
                    LOG(INFO,"信号中断");
                    continue;
                }
                //读取失败

                else{
                    LOG(INFO,"读取失败");
                    break;
                }


            }


        }
    }
    // void Accepter(Connection *conn)
    // {
    // LOG(INFO, "%d accept success\n", conn->Sockfd());

    // }
    int Sockfd()
    {
        return _listensocket->Sockfd();
    }
    ~Listener()
    {
    }

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listensocket;
};